﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Autodesk.Revit.UI;
using FsAddInManager.Utils.InitFile;
using static FsAddInManager.FsAddinApp;

namespace FsAddInManager
{
    public partial class SettingForm : Form
    {
        public const string spiltCell = "&!-Cell-!&"; //分割单元格的字符串
        public const string spiltRow = "&!-Row-!&"; //分割每行的字符串

        private string _tempPath = "";
        private string _dllName = "";

        private RibbonPanel ribbonPanel; //设置快捷键

        public string TempPath
        { 
            get
            { 
                return _tempPath;
            }
        }

        public SettingForm(RibbonPanel panel)
        {
            ribbonPanel = panel;
            InitializeComponent();

            InitByIniFile(); //初始化配置

            //暂时隐藏
            buttonGlance.Visible = false;
            textBoxPath.Enabled = false;
        }

        #region 初始化

        /// <summary>
        /// 读取配置文件中的默认值
        /// </summary>
        private void InitByIniFile()
        {
            #region 初始化通用配置

            //1.1 加载通用设置的配置文件
            InitFile iniProfile = new InitFile(FsAppBase.DefaultIniPath);

            //1.2 为项目列表赋值
            List<string> dllNames = GetDllNameList();
            if (dllNames.Count > 0)
            {
                foreach (var name in dllNames)
                {
                    int rowIndex = gridViewDll.Rows.Add();
                    gridViewDll.Rows[rowIndex].Cells[0].Value = name;
                }
            }

            //1.3 为“快捷键”赋值
            string selectKey = "";
            bool isOK3 = iniProfile.GetValueOfKey("KeyBoardDim", "SelectKeyBoard", ref selectKey);
            if (isOK3)
            {
                textBoxSelect.Text = selectKey;
            }

            string repeatKey = "";
            bool isOK4 = iniProfile.GetValueOfKey("KeyBoardDim", "RepeatKeyBoard", ref repeatKey);
            if (isOK4)
            {
                textBoxRepeat.Text  = repeatKey;
            }

            #endregion

            #region 项目配置

            //1.1 加载所选DLL的配置文件
            string dllName = "";
            bool isOK6 = iniProfile.GetValueOfKey("SelectDllDim", "DllName", ref dllName); //加载上次选择的DLL
            if (isOK6 && gridViewDll.Rows.Count > 0)
            {
                //遍历
                for (int i = 0; i < gridViewDll.Rows.Count; i++)
                {
                    if (gridViewDll.Rows[i].Cells[0].Value.ToString() == dllName)
                    {
                        //gridViewDll.Rows[i].Selected = true;
                        gridViewDll.CurrentCell = gridViewDll[0, i];
                    }
                }
            }
            else
            {
                if (gridViewDll.Rows.Count > 0)
                {
                    gridViewDll.CurrentCell = gridViewDll[0, 0];  //如果配置文件中没有上次选择的数据，则默认选择第一行
                    dllName = gridViewDll.Rows[0].Cells[0].Value.ToString();
                }
            }

            //1.2 为右侧控件赋值
            if (dllNames.Count > 0 && !string.IsNullOrEmpty(dllName))
            {
                LoadInitFile(dllName);
            }

            #endregion
        }

        #endregion

        #region 窗体方法-创建配置文件部分

        /// <summary>
        /// 创建项目的配置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAddInit_Click(object sender, EventArgs e)
        {
            var form = new DllNameForm();
            if (form.ShowDialog() == DialogResult.OK)
            {
                string dllName = form.DllName + ".ini";

                if (!File.Exists(FsAppBase.DefaultDirPath + "\\" + dllName))
                {
                    File.Create(FsAppBase.DefaultDirPath + "\\" + dllName).Close();

                    int rowIndex = gridViewDll.Rows.Add(); //增添一行
                    gridViewDll.Rows[rowIndex].Cells[0].Value = dllName;

                    CancelSelectRow(gridViewDll);//取消所有选中
                    gridViewDll.CurrentCell = gridViewDll[0, rowIndex]; //设置选中
                    gridViewDll.Rows[rowIndex].Selected = true;

                    //清空
                    Clear();

                    //手动触发行切换事件
                    gridViewDll_RowEnter(null,null);   
                }                

                LoadInitFile(dllName); //加载配置文件
            }
        }

        /// <summary>
        /// 取消所有选中行
        /// </summary>
        private void CancelSelectRow(DataGridView gridView)
        {
            for(int i = 0; i <  gridView.Rows.Count; i++)
            {
                gridView.Rows[i].Selected = false;
            }
        }

        /// <summary>
        /// 复制项目配置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCopyInit_Click(object sender, EventArgs e)
        {
            try
            {
                if (gridViewDll.Rows.Count == 0)
                {
                    return;
                }

                //获得选择的配置文件路径
                string sourcePath = FsAppBase.DefaultDirPath + "\\" + gridViewDll.CurrentCell.Value.ToString();

                var form = new DllNameForm();
                if (form.ShowDialog() == DialogResult.OK)
                {
                    string destName = form.DllName + ".ini";
                    string destPath = FsAppBase.DefaultDirPath + "\\" + destName;

                    File.Copy(sourcePath, destPath,false);    
                    
                    int rowIndex = gridViewDll.Rows.Add(); //增添一行
                    gridViewDll.Rows[rowIndex].Cells[0].Value = destName;

                    CancelSelectRow(gridViewDll);//取消所有选中
                    gridViewDll.CurrentCell = gridViewDll[0, rowIndex]; //设置选中
                    gridViewDll.Rows[rowIndex].Selected = true;

                    //清空
                    Clear();

                    //手动触发行切换事件
                    gridViewDll_RowEnter(null,null);                    
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show("复制失败！请检查文件是否存在或者是否有同名文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
        }

        /// <summary>
        /// 打开配置文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonOpenInit_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(FsAppBase.DefaultDirPath))
            {
                System.Diagnostics.Process.Start(FsAppBase.DefaultDirPath);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonDeleteInit_Click(object sender, EventArgs e)
        {
            try
            {
                if (File.Exists(FsAppBase.DefaultDirPath + "\\" + _dllName))
                {
                    File.Delete(FsAppBase.DefaultDirPath + "\\" + _dllName);

                    //删除一行
                    gridViewDll.Rows.Remove(gridViewDll.CurrentRow);

                    labelTips.Text = "删除addin文件成功！";
                    labelTips.ForeColor = Color.ForestGreen;

                    //清空
                    Clear();

                    //手动触发行切换事件
                    gridViewDll_RowEnter(null,null);
                }
                else
                { 
                    return;
                }
            }
            catch (Exception ex)
            {
                labelTips.Text = "删除addin文件失败！请使用管理员权限启动.";
                labelTips.ForeColor = Color.Red;
            }
        }

        /// <summary>
        /// 项目列表-行切换事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridViewDll_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (gridViewDll.CurrentCell == null) return;
            //if (e.RowIndex < 0 || e.ColumnIndex < 0) return;

            string dllName = gridViewDll.SelectedCells[0].Value.ToString();
            if (!string.IsNullOrEmpty(dllName))
            {
                LoadInitFile(dllName); //加载配置文件
            }
        }

        #endregion

        #region 窗体方法-快捷键部分

        /// <summary>
        /// 快捷键“应用”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonApply_Click(object sender, EventArgs e)
        {
            //1.保存快捷键到配置文件
            InitFile profile = new InitFile(FsAppBase.DefaultIniPath);
            profile.SetValueOfKey("KeyBoardDim", "SelectKeyBoard", textBoxSelect.Text);
            profile.SetValueOfKey("KeyBoardDim", "RepeatKeyBoard", textBoxRepeat.Text);
            profile.SetValueOfKey("KeyBoardDim", "ShortCutKeyBoard", textBoxSet.Text);

            //2.将快捷键应用到revit设置
            Setting.SetShortCut(ribbonPanel);

            labelTips.Text = "应用并保存快捷键成功！";
            labelTips.ForeColor = Color.ForestGreen;
        }

        /// <summary>
        /// 超链接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            linkLabel1.LinkVisited = true;
            Process.Start("IExplore", "https://jq.qq.com/?_wv=1027&k=LHLHPhFr");
        }

        /// 关闭窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }        

        #endregion

        #region 窗体方法-调试路径部分

        /// <summary>
        /// “浏览”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonGlance_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                textBoxPath.Text = _tempPath = dlg.SelectedPath;
                
                InitFile profile = new InitFile(FsAppBase.DefaultIniPath);
                profile.SetValueOfKey("GlancePathDim", "GlancePath", dlg.SelectedPath);
            }
        }

        /// <summary>
        /// “打开”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonOpen_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(_tempPath) && Directory.Exists(_tempPath))
            {
                System.Diagnostics.Process.Start(_tempPath);
            }
        }

        /// <summary>
        /// “清空”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonClearTemp_Click(object sender, EventArgs e)
        {
            //注册确定取消按钮
     	    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("确定要清空吗?", "清空", messButton);

            if (dr == DialogResult.OK && !string.IsNullOrEmpty(_tempPath) && Directory.Exists(_tempPath))
            {
                DelectDir(_tempPath);

                labelTips.Text = "清除成功！";
                labelTips.ForeColor = Color.ForestGreen;
            }
        }

        #endregion

        #region 窗体方法-资源文件配置部分  

        /// <summary>
        /// “添加”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            //新增一行
            gridViewPath.Rows.Add();
        }

        /// <summary>
        /// “删除”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            //删除一行
            gridViewPath.Rows.Remove(gridViewPath.SelectedRows[0]);
        }

        /// <summary>
        /// “清空”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonClear_Click(object sender, EventArgs e)
        {
            //删除所有行
            gridViewPath.Rows.Clear();
        }

        /// <summary>
        /// “执行”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonExecute_Click(object sender, EventArgs e)
        {
            bool flag = true;

            //通过路径信息进行复制
            foreach (DataGridViewRow row in gridViewPath.Rows)
            {
                if(!CopyDirectory(row.Cells[0].Value.ToString(),row.Cells[1].Value.ToString()))
                { 
                    labelTips.Text = "执行失败！该目录不存在.";
                    labelTips.ForeColor = Color.Red;
                    flag = false;
                    return;
                }
            }

            if(flag)
            { 
                labelTips.Text = "执行成功！";
                labelTips.ForeColor = Color.ForestGreen;
            }
        }

        /// <summary>
        /// “保存”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSave_Click(object sender, EventArgs e)
        {
            string viewContent = "";
            foreach (DataGridViewRow row in gridViewPath.Rows)
            {
                if (row.Cells[0].Value.Equals(row.Cells[1].Value))
                {
                    labelTips.Text = "保存失败！源路径和目标路径不能相同！";
                    labelTips.ForeColor = Color.Red;
                    return;
                }

                viewContent += row.Cells[0].Value + spiltCell + row.Cells[1].Value + spiltCell + (string.IsNullOrEmpty(row.Cells[2].Value + "") ? "False" : "True") + spiltRow;
            }

            //进行保存
            InitFile profile = new InitFile(FsAppBase.DefaultDirPath + "\\" + _dllName);
            bool isOK = profile.SetValueOfKey("DataViewPathDim", "DataViewPath", viewContent);

            if(isOK)
            { 
                labelTips.Text = "保存成功！";
                labelTips.ForeColor = Color.ForestGreen;   
            }
            else
            { 
                labelTips.Text = "保存失败！";
                labelTips.ForeColor = Color.Red;  
            }
        }

        #endregion

        #region 内部方法

        /// <summary>
        /// 获取项目文件的名称
        /// </summary>
        /// <returns></returns>
        private List<string> GetDllNameList()
        {
            try
            {
                List<string> dllNameList = new List<string>();

                DirectoryInfo dir = new DirectoryInfo(FsAppBase.DefaultDirPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //获取目录下（不包含子目录）的文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (!i.Name.Equals("FsAddinSetting.ini")) //判断是否是通用配置文件
                    {
                        dllNameList.Add(i.Name);
                    }
                }

                return dllNameList;
            }
            catch (Exception e)
            {
                throw;
            }
        }

        /// <summary>
        /// 复制文件夹
        /// </summary>
        /// <param name="srcPath">源文件夹路径</param>
        /// <param name="destPath">目标文件夹路径</param>
        public static bool CopyDirectory(string srcPath, string destPath)
        {
            try
            {
                if(Directory.Exists(srcPath))
                { 
                    DirectoryInfo dir = new DirectoryInfo(srcPath);
                    FileSystemInfo[] fileinfo = dir?.GetFileSystemInfos(); //获取目录下（不包含子目录）的文件和子目录
                    if(fileinfo != null)
                    { 
                        foreach (FileSystemInfo i in fileinfo)
                        {
                            if (i is DirectoryInfo) //判断是否文件夹
                            {
                                if (!Directory.Exists(destPath + "\\" + i.Name))
                                {
                                    Directory.CreateDirectory(destPath + "\\" + i.Name); //目标目录下不存在此文件夹即创建子文件夹
                                }
                                CopyDirectory(i.FullName, destPath + "\\" + i.Name); //递归调用复制子文件夹
                            }
                            else
                            {
                                File.Copy(i.FullName, destPath + "\\" + i.Name,true); //不是文件夹即复制文件，true表示可以覆盖同名文件
                            }
                        }
                    }

                    return true;
                }
                else
                { 
                    return false;
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="srcPath"></param>
        public static void DelectDir(string srcPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    } 
                    else
                    {
                        File.Delete(i.FullName);      //删除指定文件
                    }
                }                
            }
            catch (Exception e)
            {
                MessageBox.Show("删除失败！权限不足,请手动删除.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 清空
        /// </summary>
        private void Clear()
        {
            textBoxPath.Text = "";
            gridViewPath.Rows.Clear();
        }

        /// <summary>
        /// 加载dll的配置文件
        /// </summary>
        /// <param name="dllName"></param>
        private void LoadInitFile(string dllName)
        {
            _dllName = dllName; //存储项目名称
            gridViewPath.Rows.Clear(); //先清空再加载

            //存储项目名称
            InitFile iniProfile = new InitFile(FsAppBase.DefaultIniPath);
            iniProfile.SetValueOfKey("SelectDllDim", "DllName", dllName);

            //为“调试路径”赋值
            string addinPath = "";
            InitFile profile = new InitFile(FsAppBase.DefaultDirPath + "\\" + dllName);
            bool isOK1 = profile.GetValueOfKey("GlancePathDim", "GlancePath", ref addinPath);
            if (isOK1)
            {
                textBoxPath.Text = _tempPath = addinPath;
            }

            //若没有从配置文件中获得，则读取addin调试的默认临时文件夹
            if (string.IsNullOrEmpty(addinPath))
            {
                string tempPath = Path.GetTempPath();
                addinPath = Path.Combine(tempPath, "RevitAddins");
                textBoxPath.Text = _tempPath = addinPath;
            }

            //为“资源文件”的gridView赋值
            string pathData = "";
            bool isOK2 = profile.GetValueOfKey("DataViewPathDim", "DataViewPath", ref pathData);

            if (isOK2)
            {
                List<string> rowContents = new List<string>(pathData.Split(new string[] { spiltRow }, StringSplitOptions.RemoveEmptyEntries));
                
                foreach (var row in rowContents)
                {
                    List<string> cellContents = new List<string>(row.Split(new string[] { spiltCell }, StringSplitOptions.None));
                    int rowIndex = gridViewPath.Rows.Add();
                    gridViewPath.Rows[rowIndex].Cells[0].Value = cellContents[0];
                    gridViewPath.Rows[rowIndex].Cells[1].Value = cellContents[1];
                    gridViewPath.Rows[rowIndex].Cells[2].Value = cellContents[2];
                }
            }
        }

        #endregion
    }
}
